<template>
  <a-card :bordered="false">
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button
        v-if="addFlag"
        @click="handleAdd"
        type="primary"
        icon="plus"
        :disabled="isDisabledAuth('erpPurchaseWarehouseWarrantDetail:add')"
        :hidden="disabled">新增</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="warrantType ==5? {x:'120%'} : {x:'200%'}"
        bordered
        rowKey="key"
        :columns="defColumns"
        :dataSource="dataSource"
        :pagination="false"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">
        <!-- 送货数量标题定制 -->
        <span slot="deliveryNumTitle"><span style="color: red; text-align: center;">*</span> 送货数量</span>
        <!-- 退回数量标题定制 -->
        <span slot="returnNumTitle"><span style="color: red; text-align: center;">*</span> 退回数量</span>
        <!-- 存放仓库标题定制 -->
        <span slot="storehouseIdTitle"><span style="color: red; text-align: center;">*</span> 存放仓库</span>
        <!-- 有效期单位标题定制 -->
        <span slot="periodValidityUnitTitle"><span style="color: red; text-align: center;">*</span> 有效期单位</span>

        <!-- 供应商 -->
        <span slot="companName" slot-scope="text, record">
          <select-customer-input v-if="!disabled" placeholder="请选择供应商名称" :disabled="disabled" commercialType="2" v-model="record.companName"/>
          <span v-else :title="filterMultiDictText(dictOptions['companName'], text + '')">{{ filterMultiDictText(dictOptions['companName'], text + '') }}</span>
        </span>

        <!-- 送货数量 -->
        <template slot="deliveryNum" slot-scope="text, record">
          <a-input-number
            v-if="!disabled"
            :disabled="disabled"
            :max="99999999"
            :min="1"
            :precision="0"
            v-model="record.deliveryNum"
            placeholder="请输入"
            style="width: 100%" />
          <span v-else :title="record.deliveryNum">{{ text }}</span>
        </template>
        <!-- 退回数量 -->
        <template slot="returnNum" slot-scope="text, record">
          <a-input-number
            v-if="!disabled"
            :disabled="disabled"
            :max="record.deliveryNum?Number(record.deliveryNum):0"
            :min="0"
            :precision="0"
            v-model="record.returnNum"
            placeholder="请输入"
            style="width: 100%" />
          <span v-else :title="record.returnNum">{{ text }}</span>
        </template>
        <!-- 入库数量 -->
        <template slot="warrantNum" slot-scope="text, record, index">
          <span :title="record.warrantNum">{{ getWarrantNum(text, record, index) }}</span>
        </template>

        <!-- 存放仓库 -->
        <template slot="storehouseId" slot-scope="text, record">
          <a-select
            v-model="record.storehouseId"
            v-if="!disabled"
            :disabled="disabled"
            placeholder="请选择存放仓库"
            :showSearch="true"
            :allowClear="true"
            :filterOption="filterOption"
            @change="(arg) => { changeStore(arg, record) }"
          >
            <a-select-option v-for="item in foldWarehouseList" :key="item.id" :value="item.id">{{ item.categoryName }}</a-select-option>
          </a-select>
          <span v-else :title="filterMultiDictText(dictOptions['storehouseId'], text + '')">{{ filterMultiDictText(dictOptions['storehouseId'], text + '') }}</span>
        </template>

        <!-- 生产日期 -->
        <template slot="dateProduced" slot-scope="text, record">
          <a-date-picker
            v-if="!disabled"
            style="width: 100%"
            :disabled="disabled"
            placeholder="请选择"
            v-model="record.dateProduced"
            :disabled-date="disabledDate"
            format="YYYY-MM-DD"
          />
          <!-- @change="handleDateChange" -->
          <span v-else :title="record.dateProduced">{{ text }}</span>
        </template>

        <!-- 有效期 -->
        <template slot="periodValidity" slot-scope="text, record">
          <!-- @change="periodValiditychange" -->
          <a-input-number
            :disabled="disabled"
            v-if="!disabled"
            :min="1"
            :precision="0"
            v-model="record.periodValidity"
            style="width: 50%;"
            placeholder="请输入" />
          <span v-else :title="record.periodValidity">{{ text?text + filterMultiDictText(dictOptions['periodValidityUnit'], record.periodValidityUnit + ''): '' }}</span>
          <j-dict-select-tag
            :disabled="disabled"
            v-if="!disabled && record.periodValidity"
            type="list"
            style="width: 50%;"
            v-model="record.periodValidityUnit"
            placeholder="请选择有效期单位"
            dictCode="period_validity_unit"/>
          
        </template>

        <!-- 有效期单位 -->
        <!-- <template slot="periodValidityUnit" slot-scope="text, record">
          <j-dict-select-tag
            :disabled="disabled"
            v-if="!disabled"
            type="list"
            v-model="record.periodValidityUnit"
            placeholder="请选择"
            dictCode="period_validity_unit"/>
          <span v-else :title="record.periodValidityUnit">{{ text }}</span>
        </template> -->

        <!-- 备注 -->
        <template slot="remark" slot-scope="text, record">
          <a-textarea
            :disabled="disabled"
            v-if="!disabled"
            :max-length="100"
            v-model="record.remark"
            :auto-size="{ minRows: 2, maxRows: 2 }"
            placeholder="请输入备注"/>
          <span v-else :title="record.remark">{{ text }}</span>
        </template>

        <span slot="action" slot-scope="text, record">
          <template v-if="warrantType != 5">
            <a-button
              class="ruleButton"
              :ghost="true"
              type="primary"
              icon="edit"
              :hidden="disabled"
              @click="handleEdit(record)"
              :disabled="isDisabledAuth('erpPurchaseWarehouseWarrantDetail:edit')"
            />
            <a-divider type="vertical"/>
          </template>
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.key)">
            <a-button
              class="ruleButton"
              :ghost="true"
              type="primary"
              icon="delete"
              :hidden="disabled"
              :disabled="isDisabledAuth('erpPurchaseWarehouseWarrantDetail:delete')"/>
          </a-popconfirm>
        </span>

      </a-table>
    </div>

    <erp-purchase-warehouse-warrant-detail-modal ref="modalForm" @dataOne="dataOne"></erp-purchase-warehouse-warrant-detail-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  // import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import moment from 'moment'
  import ErpPurchaseWarehouseWarrantDetailModal from './ErpPurchaseWarehouseWarrantDetailModal'
  import SelectCustomerInput from '@/views/scy/components/SelectCustomerInput'
  import { filterObj } from '@/utils/util'
  import { DisabledAuthFilterMixin } from '@/mixins/DisabledAuthFilterMixin'
  import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
  import Vue from 'vue'
  import { getAction } from '@/api/manage'
  export default {
    name: 'ErpPurchaseWarehouseWarrantDetailList',
    mixins: [ mixinDevice, DisabledAuthFilterMixin],
    components: {
      ErpPurchaseWarehouseWarrantDetailModal,
      SelectCustomerInput
    },
    props: {
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      storer: {
        type: String,
        default: '',
        required: false
      },
      warrantType: {
        type: String,
        default: '',
        required: false
      }
    },
    watch: {
      storer: {
        handler (val) {
          if (val) {
            this.handleChangeFoldApplicant(val)
          }
        },
        immediate: true
      }
    },
    data () {
      return {
        description: '入库单明细管理页面',
        filterMultiDictText,
        foldWarehouseList: [], // 仓库列表
        queryParam: {},
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30', '50', '100', '200'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        /* 排序参数 */
        isorter: {
          column: 'createTime',
          order: 'desc'
        },
        /* 筛选参数 */
        filters: {},
        /* table加载状态 */
        loading: false,
        /* table选中keys */
        selectedRowKeys: [],
        /* table选中records */
        selectionRows: [],
        /* 查询折叠 */
        toggleSearchStatus: false,
        /* 高级查询条件生效状态 */
        superQueryFlag: false,
        /* 高级查询条件 */
        superQueryParams: '',
        /** 高级查询拼接方式 */
        superQueryMatchType: 'and',
        iconStyle: { 'font-size': '18px', 'cursor': 'pointer' },
        colsettings: ':colsettings',
        // 表头
        columns: [],
        // 列设置
        settingColumns: [],
        // 列定义
        defColumns: [],
        defColumnsOne: [
          {
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '物料大类',
            align: 'center',
            dataIndex: 'provisionBroad',
            ellipsis: true,
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['provisionBroad'], text + '')
              }
            }
          },
          {
            title: '物料小类',
            align: 'center',
            dataIndex: 'provisionSmall',
            ellipsis: true,
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['provisionSmall'], text + '')
              }
            }
          },
          {
            title: '物料编号',
            align: 'center',
            dataIndex: 'materialBillId',
            ellipsis: true
          },
          {
            title: '物料名称',
            align: 'center',
            dataIndex: 'materialName',
            ellipsis: true,
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['materialName'], text + '')
              }
            }
          },
          {
            title: '规格型号',
            align: 'center',
            dataIndex: 'specification',
            ellipsis: true
          },
          {
            title: '单位',
            align: 'center',
            dataIndex: 'unit',
            ellipsis: true,
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['unit'], text + '')
              }
            }
          },
          {
            title: '品牌',
            align: 'center',
            dataIndex: 'brand',
            ellipsis: true
          },
          {
            title: '供应商',
            align: 'center',
            dataIndex: 'companName',
            key: 'companName',
            ellipsis: true,
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['companName'], text + '')
              }
            }
          },
          {
            title: '采购数量',
            align: 'center',
            dataIndex: 'purchaseNum',
            ellipsis: true
          },
          {
            title: '累计已入库数量',
            align: 'center',
            dataIndex: 'warrantAmount',
            ellipsis: true
          },
          {
            title: '本次送货数量',
            align: 'center',
            dataIndex: 'deliveryNum',
            ellipsis: true
          },
          {
            title: '本次退回数量',
            align: 'center',
            dataIndex: 'returnNum',
            ellipsis: true
          },
          {
            title: '本次入库数量',
            align: 'center',
            dataIndex: 'warrantNum',
            ellipsis: true
          },
          {
            title: '存放仓库',
            align: 'center',
            dataIndex: 'storehouseId',
            ellipsis: true,
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['storehouseId'], text + '')
              }
            }
          },
          {
            title: '生产日期',
            align: 'center',
            dataIndex: 'dateProduced',
            ellipsis: true,
            customRender: function (text) {
              return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
            }
          },
          {
            title: '有效期',
            align: 'center',
            dataIndex: 'periodValidity',
            ellipsis: true
          },
          {
            title: '有效期单位',
            align: 'center',
            dataIndex: 'periodValidityUnit',
            ellipsis: true,
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['periodValidityUnit'], text + '')
              }
            }
          },
          {
            title: '备注',
            align: 'center',
            dataIndex: 'remark',
            ellipsis: true
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            fixed: 'right',
            width: 147,
            scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action' }
          }
        ],
        defColumnsTwo: [
          {
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '物料大类',
            align: 'center',
            dataIndex: 'provisionBroad',
            ellipsis: true,
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['provisionBroad'], text + '')
              }
            }
          },
          {
            title: '物料小类',
            align: 'center',
            dataIndex: 'provisionSmall',
            ellipsis: true,
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['provisionSmall'], text + '')
              }
            }
          },
          {
            title: '物料编号',
            align: 'center',
            dataIndex: 'materialBillId',
            ellipsis: true
          },
          {
            title: '物料名称',
            align: 'center',
            dataIndex: 'materialName',
            ellipsis: true,
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['materialName'], text + '')
              }
            }
          },
          {
            title: '规格型号',
            align: 'center',
            dataIndex: 'specification',
            ellipsis: true
          },
          {
            title: '单位',
            align: 'center',
            dataIndex: 'unit',
            ellipsis: true,
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['unit'], text + '')
              }
            }
          },
          {
            title: '品牌',
            align: 'center',
            dataIndex: 'brand',
            ellipsis: true
          },
          {
            title: '供应商',
            align: 'center',
            dataIndex: 'companName',
            key: 'companName',
            ellipsis: true,
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['companName'], text + '')
              }
            }

          },
          {
            title: '领用数量',
            align: 'center',
            dataIndex: 'purchaseNum',
            ellipsis: true
          },
          {
            title: '领用返还数量',
            align: 'center',
            dataIndex: 'deliveryNum',
            ellipsis: true
          },
          {
            title: '退回数量',
            align: 'center',
            dataIndex: 'returnNum',
            ellipsis: true
          },
          {
            title: '入库数量',
            align: 'center',
            dataIndex: 'warrantNum',
            ellipsis: true
          },
          {
            title: '存放仓库',
            align: 'center',
            dataIndex: 'storehouseId',
            ellipsis: true,
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['storehouseId'], text + '')
              }
            }
          },
          {
            title: '生产日期',
            align: 'center',
            dataIndex: 'dateProduced',
            ellipsis: true,
            customRender: function (text) {
              return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
            }
          },
          {
            title: '有效期',
            align: 'center',
            dataIndex: 'periodValidity',
            ellipsis: true
          },
          {
            title: '有效期单位',
            align: 'center',
            dataIndex: 'periodValidityUnit',
            ellipsis: true,
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['periodValidityUnit'], text + '')
              }
            }
          },
          {
            title: '备注',
            align: 'center',
            dataIndex: 'remark',
            ellipsis: true
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            fixed: 'right',
            width: 147,
            scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action' }
          }
        ],
        defColumnsThree: [
          {
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '物料大类',
            align: 'center',
            width: 80,
            dataIndex: 'provisionBroad',
            ellipsis: true,
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['provisionBroad'], text + '')
              }
            }
          },
          {
            title: '物料小类',
            align: 'center',
            dataIndex: 'provisionSmall',
            ellipsis: true,
            width: 80,
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['provisionSmall'], text + '')
              }
            }
          },
          {
            title: '物料编号',
            align: 'center',
            width: 80,
            dataIndex: 'materialBillId',
            ellipsis: true
          },
          {
            title: '物料名称',
            align: 'center',
            dataIndex: 'materialName',
            ellipsis: true,
            width: 80,
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['materialName'], text + '')
              }
            }
          },
          {
            title: '规格型号',
            align: 'center',
            width: 80,
            dataIndex: 'specification',
            ellipsis: true
          },
          {
            title: '单位',
            align: 'center',
            width: 60,
            dataIndex: 'unit',
            ellipsis: true,
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['unit'], text + '')
              }
            }
          },
          {
            title: '品牌',
            align: 'center',
            width: 80,
            dataIndex: 'brand',
            ellipsis: true
          },
          {
            title: '供应商',
            align: 'center',
            dataIndex: 'companName',
            key: 'companName',
            width: 200,
            scopedSlots: { customRender: 'companName' },
            ellipsis: true
          },

          // 送货数量
          {
            // title: '送货数量',
            slots: { title: 'deliveryNumTitle' },
            align: 'center',
            width: 85,
            dataIndex: 'deliveryNum',
            ellipsis: true,
            key: 'deliveryNum',
            scopedSlots: { customRender: 'deliveryNum' }
          },
          // 退回数量
          {
            // title: '退回数量',
            slots: { title: 'returnNumTitle' },
            align: 'center',
            width: 85,
            dataIndex: 'returnNum',
            ellipsis: true,
            key: 'returnNum',
            scopedSlots: { customRender: 'returnNum' }
          },
          {
            title: '入库数量',
            align: 'center',
            width: 80,
            dataIndex: 'warrantNum',
            ellipsis: true,
            key: 'warrantNum',
            scopedSlots: { customRender: 'warrantNum' }
          },
          // 存放仓库
          {
            // title: '存放仓库',
            slots: { title: 'storehouseIdTitle' },
            align: 'center',
            dataIndex: 'storehouseId',
            width: 300,
            ellipsis: true,
            key: 'storehouseId',
            scopedSlots: { customRender: 'storehouseId' }
          },
          {
            title: '生产日期',
            align: 'center',
            dataIndex: 'dateProduced',
            ellipsis: true,
            // customRender: function (text) {
            //   return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
            // }
            width: 150,
            key: 'dateProduced',
            scopedSlots: { customRender: 'dateProduced' }
          },
          {
            title: '有效期',
            align: 'center',
            dataIndex: 'periodValidity',
            ellipsis: true,
            width: 200,
            key: 'periodValidity',
            scopedSlots: { customRender: 'periodValidity' }
          },
          // 有效期单位
          // {
          //   // title: '有效期单位',
          //   slots: { title: 'periodValidityUnitTitle' },
          //   align: 'center',
          //   width: 120,
          //   dataIndex: 'periodValidityUnit',
          //   ellipsis: true,
          //   key: 'periodValidityUnit',
          //   scopedSlots: { customRender: 'periodValidityUnit' }
          // },
          {
            title: '备注',
            align: 'center',
            dataIndex: 'remark',
            width: 200,
            ellipsis: true,
            key: 'remark',
            scopedSlots: { customRender: 'remark' }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            fixed: 'right',
            width: 147,
            scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action' }
          }
        ],
        url: {
          list: '/api/erp/purchase/storehouse/erpPurchaseWarehouseWarrantDetail/allList',
          queryByStorehouseManager: '/api/erp/purchase/storehouse/erpStorehouseBase/queryByStorehouseManager'
        },
        dictOptions: {},
        superFieldList: [],
        dataSource: [],
        addFlag: true
      }
    },
    created() {
      // 加载数据字典信息
      this.initDictConfig();
      this.getSuperFieldList();
      if (!this.disableMixinCreated) {
        this.initColumns()
      }
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          '0': '待提交',
          '1': '待审核',
          '2': '已审核'
        }
        return statusMap[status] || status
      },
      statusTypeFilter(type) {
        const statusTypeMap = {
          '0': 'success',
          '1': 'success',
          '2': 'success'
        }
        return statusTypeMap[type] || 'success'
      }
    },
    computed: {
      importExcelUrl: function() {
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      }
    },
    methods: {
      handleChangeWarrantType(data) {
        if (data == 1 || data == 2) {
          this.defColumns = this.defColumnsOne
        } else if (data == 3) {
          this.defColumns = this.defColumnsTwo
        } else if (data == 5) {
          this.defColumns = this.defColumnsThree
        } else {
          this.defColumns = this.defColumnsThree
        }
      },

      disabledDate(current) {
        // Can not select days before today and today
        return current && current >= moment().endOf('day');
      },

      // 计算退回数量
      // returnMaxNum (deliveryNum, returnNum) {
      //   if (returnNum > deliveryNum) {
      //     this.$message.warning('退回数量不可超过送货数量')
      //   }
      //   if (deliveryNum) {
      //     return deliveryNum
      //   } else {
      //     return 0
      //   }
      // },
      
      // 校验当前仓库是否盘点
      changeStore(id, record){
        let storehouseId = id
        getAction('/api/erp/purchase/storehouse/erpPurchaseWarehouseWarrant/validateInProgress', { storehouseId }).then(res => {
            if (!res.success) {
                this.$message.error(res.message)
                this.$set(record, 'storehouseId', '')
            }
        })
      },
      // 仓库列表
      handleChangeFoldApplicant(v, num = 0) {
        const that = this
        getAction(this.url.queryByStorehouseManager, { storehouseManager: v }).then((res) => {
          if (res.success) {
            that.foldWarehouseList = []
            res.result.forEach((res) => {
              that.foldWarehouseList.push({ 'id': res.id, 'categoryName': res.storehouseName })
            })
            // let storehouseFlag = that.foldWarehouseList.some(item => item.id == this.model.storehouseId)
            // if (!storehouseFlag) {
            //   this.$set(this.model, 'storehouseId', undefined)
            // }
          } else {
            that.$message.warning(res.message)
          }
        })
      },

      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      initDictConfig() {
        // 物料大类
        initDictOptions('erp_material_category,category_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'provisionBroad', res.result)
          }
        })
        // 物料小类
        initDictOptions('erp_material_category,category_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'provisionSmall', res.result)
          }
        })
        // 物料名称
        initDictOptions('erp_material,material_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'materialName', res.result)
          }
        })
        // 单位
        initDictOptions('unit_type').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'unit', res.result)
          }
        })
        // 有效期单位
        initDictOptions('period_validity_unit').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'periodValidityUnit', res.result)
          }
        })
        // 存放仓库
        initDictOptions('erp_storehouse_base,storehouse_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'storehouseId', res.result)
          }
        })
        // 供应商
        initDictOptions('erp_purchase_supplier,enterprise_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'companName', res.result)
          }
        })
      },
      loadData(arg, id) {
        if (!this.url.list) {
          this.$message.error('请设置url.list属性!')
          return
        }
        // 加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1
        }
        this.params = this.getQueryParams() // 查询条件
        if (id) {
          this.params.billId = id
        }
        this.loading = true
        getAction(this.url.list, this.params).then(res => {
          if (res.success) {
            // update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result
            this.dataSource.forEach((item, index) => {
              item.key = index
            })
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
            // 判断是否当前页没有数据且不为第一页
            if (this.dataSource.length == 0 && this.ipagination.current != 1) {
              this.ipagination.current = this.ipagination.current - 1
              this.loadData(this.ipagination.current - 1);
            }
            // update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.loading = false
        })
      },
      getSelectedRowKeys() {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        return ids
      },
      getQueryParams() {
        // 获取查询条件
        let sqp = {}
        if (this.superQueryParams) {
          sqp['superQueryParams'] = encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
        param.field = this.getQueryField()
        param.pageNo = this.ipagination.current
        param.pageSize = this.ipagination.pageSize
        return filterObj(param)
      },
      getQueryField() {
        // TODO 字段权限控制
        var str = 'id'
        this.columns.forEach(function (value) {
          // 多表头字段
          if (value.dataIndex == null && value.dataIndex === undefined) {
            value.children.forEach(function (item) {
              str += ',' + item.dataIndex.replace('_dictText', '')
            })
          } else {
            str += ',' + value.dataIndex
          }
        })
        return str
      },
      handleAdd() {
        if (!this.storer) {
          this.$message.error('请选择仓管员!')
          return false
        }
        if (!this.warrantType) {
          this.$message.error('请选择入库类型!')
          return false
        }
        this.$refs.modalForm.add()
        this.$refs.modalForm.title = '新增'
        this.$refs.modalForm.storer = this.storer
        this.$refs.modalForm.warrantType = this.warrantType
        this.$refs.modalForm.disableSubmit = false
      },
      handleEdit: function (record) {
        if (!this.storer) {
          this.$message.error('请选择仓管员!')
          return false
        }
        if (!this.warrantType) {
          this.$message.error('请选择入库类型!')
          return false
        }
        this.$refs.modalForm.edit(record)
        this.$refs.modalForm.title = '编辑'
        this.$refs.modalForm.storer = this.storer
        this.$refs.modalForm.warrantType = this.warrantType
        this.$refs.modalForm.disableSubmit = false
      },
      handleDelete: function (key) {
        if (this.warrantType == '2') {
          this.$emit('checkListDel', this.dataSource[key]);
        }
        if (this.dataSource.length == 1) {
          this.dataSource = []
          return
        }
        this.dataSource.splice(key, 1);
        this.dataSource.forEach((item, index) => {
          item.key = index
        })
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectionRows = selectionRows
      },
      onClearSelected() {
        this.selectedRowKeys = []
        this.selectionRows = []
      },
      searchQuery() {
        this.loadData(1)
      },
      superQuery() {
        this.$refs.superQueryModal.show()
      },
      getSuperFieldList() {
        let fieldList = [];
        fieldList.push({ type: 'string', value: 'provisionBroad', text: '物料大类', dictCode: '' })
        fieldList.push({ type: 'string', value: 'provisionSmall', text: '物料小类', dictCode: '' })
        fieldList.push({ type: 'string', value: 'materialBillId', text: '物料编号', dictCode: '' })
        fieldList.push({ type: 'string', value: 'materialName', text: '物料名称', dictCode: '' })
        fieldList.push({ type: 'string', value: 'specification', text: '规格型号', dictCode: '' })
        fieldList.push({ type: 'string', value: 'unit', text: '单位', dictCode: '' })
        fieldList.push({ type: 'int', value: 'deliveryNum', text: '送货数量', dictCode: '' })
        fieldList.push({ type: 'int', value: 'returnNum', text: '退回数量', dictCode: '' })
        fieldList.push({ type: 'int', value: 'warrantNum', text: '入库数量', dictCode: '' })
        fieldList.push({ type: 'string', value: 'storehouseId', text: '存放仓库', dictCode: '' })
        fieldList.push({ type: 'date', value: 'dateProduced', text: '生产日期' })
        fieldList.push({ type: 'int', value: 'periodValidity', text: '有效期', dictCode: '' })
        fieldList.push({ type: 'string', value: 'periodValidityUnit', text: '有效期单位', dictCode: '' })
        fieldList.push({ type: 'string', value: 'remark', text: '备注', dictCode: '' })
        this.superFieldList = fieldList
      },

      // 获取入库数量
      getWarrantNum (text, record, index) {
        console.log('--------text, record, index, ', text, record, index)
        if (record.deliveryNum) {
          this.dataSource[index].warrantNum = Number(record.deliveryNum) - Number(record.returnNum)
          return this.dataSource[index].warrantNum
        } else {
          this.dataSource[index].warrantNum = 0
          return this.dataSource[index].warrantNum
        }
      },
      handleTableChange(pagination, filters, sorter) {
        // 分页、排序、筛选变化时触发
        this.filters = {}
        if (Object.keys(filters).length > 0) {
          for (let key in filters) {
            let value = filters[key].join(',')
            if (value) {
              if (key.indexOf('_dictText') != -1) {
                key = key.substring(0, key.indexOf('_dictText'))
              }
              this.filters[key] = value
            }
          }
        }
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field
          this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
        }
        this.ipagination = pagination
        this.loadData()
      },
      initColumns() {
        // 权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
        // this.defColumns = colAuthFilter(this.defColumns,'testdemo:');
        if (this.defColumns) {
          var key = this.$route.name + this.colsettings
          let colSettings = Vue.ls.get(key)
          if (colSettings == null || colSettings == undefined) {
            let allSettingColumns = []
            this.defColumns.forEach(function (item, i, array) {
              allSettingColumns.push(item.dataIndex)
            })
            this.settingColumns = allSettingColumns
            this.columns = this.defColumns
          } else {
            Vue.ls.set(key, colSettings, 7 * 24 * 60 * 60 * 1000)
            this.settingColumns = colSettings
            const cols = this.defColumns.filter(item => {
              if (item.key == 'rowIndex' || item.dataIndex == 'action') {
                return true
              }
              if (colSettings.includes(item.dataIndex)) {
                return true
              }
              return false
            })
            this.columns = cols
          }
        }
      },
      dataOne(data, flag, materialDetail) {
        if (flag) {
          
          if (this.warrantType == 5) {
            materialDetail.map(value => {
              this.dataSource.push({
                provisionBroad: data.provisionBroad, // 物料大类
                provisionSmall: data.provisionSmall, // 物料小类
                materialBillId: value.materialBill, // 物料编码
                materialName: value.id, // 物料名称
                brand: value.brand, // 品牌
                specification: value.specification, // 规格型号
                referencePrice: value.referencePrice, // 参考价格
                unit: value.unit, // 单位
                deliveryNum: '', // 送货数量
                returnNum: '', // 退回数量
                warrantNum: value.warrantNum, // 入库数量
                storehouseId: undefined, // 存放仓库
                dateProduced: '', // 生产日期
                periodValidity: undefined, // 有效期
                periodValidityUnit: '', // 有效期单位
                remark: '' // 备注
              })
            })
          } else {
            this.dataSource.push(data)
          }
          this.dataSource.forEach((item, index) => {
            item.key = index
          })
        } else {
          this.dataSource.splice(data.key, 1, data);
        }
      },
      submitForm() {
        return this.dataSource
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>
